package view;

import model.ChessBoard;
import thread.AudioPlayerThread;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 游戏房间界面.
 *
 * @author 任禹名
 */
public class Room extends JFrame {
    private int limit = setLimit();
    private GameFrame gameFrame;
    private final int BLACK = 1, WHITE = 2;
    private int chooseColor = setColor();
    private ChessBoard chessBoard;
    private JPanel roomBackground = new JPanel() {
        protected void paintComponent(Graphics g) {
            Image image = new ImageIcon("resource/img/room.png").getImage();
            g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
        }
    };
    JPanel ButtonPanel = new JPanel();

    JButton restartButton = new JButton("重新开始");
    JButton exitButton = new JButton("退出本局");
    JButton regretButton = new JButton("悔棋");
    JButton giveInButton = new JButton("认输");

    public int getLimit() {
        return limit;
    }

    public int getChooseColor() {
        return chooseColor;
    }

    /**
     * 构造函数，生成一个Room对象.
     *
     * @param gameFrame
     * @param mode
     */
    public Room(GameFrame gameFrame, int mode) {
        this.gameFrame = gameFrame;
        initChessBoard(mode);
        initRoomFrame();
        addAction();
        this.setVisible(true);
    }

    /**
     * 根据mode不同，生成棋盘.
     *
     * @param mode
     * @see ChessBoard
     */
    private void initChessBoard(int mode) {
        if (mode == 0) {
            chessBoard = new ChessBoard(this, false);
        } else {
            chessBoard = new ChessBoard(this, mode);
        }
        chessBoard.setBounds(215, 100, 545, 545);
    }

    /**
     * 初始化房间GUI.
     */
    private void initRoomFrame() {
        this.setTitle("五子棋");
        this.setSize(1000, 800);
        this.setLocation((GameFrame.screenWidth - 1000) / 2, (GameFrame.screenHeight - 800) / 2);
        this.setResizable(false);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.getContentPane().setLayout(null);


        roomBackground.setBounds(0, 0, 1000, 800);
        roomBackground.setLayout(null);
        roomBackground.setOpaque(false);
        roomBackground.add(chessBoard);
        this.getContentPane().add(roomBackground);

        initButtonPanel();

    }

    /**
     * 初始化按钮位置.
     */
    private void initButtonPanel() {
        ButtonPanel.setBounds(173, 670, 515, 33);
        roomBackground.add(ButtonPanel);
        ButtonPanel.setLayout(null);
        ButtonPanel.setOpaque(false);

        restartButton.setBounds(150, 5, 80, 23);
        exitButton.setBounds(416, 5, 73, 23);
        regretButton.setBounds(240, 5, 78, 23);
        giveInButton.setBounds(328, 5, 78, 23);

        ButtonPanel.add(restartButton);
        ButtonPanel.add(exitButton);
        ButtonPanel.add(regretButton);
        ButtonPanel.add(giveInButton);
    }

    /**
     * 统一为按钮添加Action.
     */
    private void addAction() {
        restartButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                resetGame();
            }
        });
        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                resetGame();
                toOut();
            }
        });
        regretButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String[] options = {"确认悔棋", "取消悔棋"};
                int res = JOptionPane.showOptionDialog(null, "确认悔棋吗，你还有" + chessBoard.getLimit() + "次悔棋机会", "悔棋?",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.YES_NO_OPTION,
                        new ImageIcon("resource/img/back.png"), options, options[0]);
                if (res == 0) {
                    chessBoard.back();
                }


            }
        });
        giveInButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String[] options = {"确定认输", "继续本局"};
                int res = JOptionPane.showOptionDialog(null, "确定认输吗？", "这样真的好吗?",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.YES_NO_OPTION,
                        new ImageIcon("resource/img/touxiang.png"), options, options[0]);
                if (res == 0) {
                    resetGame();
                    defeat();
                }


            }
        });
    }

    /**
     * 重置游戏.
     */
    private void resetGame() {
        chessBoard.getChessAction().reset();
        repaint();
        chessBoard.setChessCnt(0);
        chessBoard.setLimit(this.limit);
        chessBoard.setLock(false);
        chessBoard.robotReset();
    }

    /**
     * 游戏失败Dialog.
     */
    public void defeat() {
        new Thread(new AudioPlayerThread("resource/audio/loser.wav")).start();
        JOptionPane.showMessageDialog(this,
                "胜败乃兵家常事，壮士请重新来过", "你输了！", JOptionPane.ERROR_MESSAGE, new ImageIcon("resource/img/loser.png"));
        resetGame();
    }

    /**
     * 人机模式获胜Dialog.
     */
    public void win() {
        new Thread(new AudioPlayerThread("resource/audio/winner.wav")).start();
        JOptionPane.showMessageDialog(this,
                "大侠，在下甘拜下风！！", "你赢了！", JOptionPane.ERROR_MESSAGE, new ImageIcon("resource/img/winner.png"));
        resetGame();
    }

    /**
     * 人人模式获胜Dialog.
     */
    public void win(int colorWin) {
        String colorString = "黑棋";
        if (colorWin == WHITE)
            colorString = "白棋";
        new Thread(new AudioPlayerThread("resource/audio/winner.wav")).start();
        JOptionPane.showMessageDialog(this,
                colorString + "赢了！", "在下甘拜下风！！", JOptionPane.ERROR_MESSAGE, new ImageIcon("resource/img/winner.png"));
        resetGame();
    }

    /**
     * 游戏平局Dialog.
     */
    public void gameDraw() {
        new Thread(new AudioPlayerThread("resource/audio/winner.wav")).start();
        JOptionPane.showMessageDialog(this,
                "平局", "势均力敌！", JOptionPane.ERROR_MESSAGE, new ImageIcon("resource/img/winner.png"));
        resetGame();
    }

    /**
     * 退出游戏界面，返回大厅.
     */
    public void toOut() {
        gameFrame.setVisible(true);
        this.dispose();
    }

    /**
     * 悔棋次数用尽Dialog.
     */
    public void noRegretTimes() {
        // TODO Auto-generated method stub
        JOptionPane.showMessageDialog(this, "你的次数已用尽");
    }

    /**
     * 棋盘上没有棋Dialog.
     */
    public void noChess() {
        // TODO Auto-generated method stub
        JOptionPane.showMessageDialog(this, "无棋可悔");
    }

    /**
     * 设置悔棋次数Dialog.
     */
    public int setLimit() {
        // TODO Auto-generated method stub
        String lim = JOptionPane.showInputDialog("请输入最大悔棋次数（0~30）");
        int ans;
        try {
            ans = Integer.parseInt(lim);
        } catch (Exception e) {
            e.printStackTrace();
            ans = 5;
        }
        if (ans > 30 || ans < 0) {
            ans = 5;
        }
        return ans;
    }

    /**
     * 选择棋子颜色Dialog.
     */
    public int setColor() {
        // TODO Auto-generated method stub
        String[] options = {"白棋", "黑棋"};
        int res = JOptionPane.showOptionDialog(this, "黑子先走，选择你的棋子颜色", "选择",
                JOptionPane.DEFAULT_OPTION, JOptionPane.YES_NO_OPTION, new ImageIcon("resource/img/winner.png"), options, options[0]);
        if (res == 0) {
            return WHITE;
        }

        return BLACK;
    }
}
